<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="项目" v-bind="validateInfos.projectId">
	          <j-dict-select-tag v-model:value="formData.projectId" dictCode="tm_project,project_name,id" placeholder="请选择项目" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="系统" v-bind="validateInfos.projectSystemId">
	          <j-dict-select-tag v-model:value="formData.projectSystemId" dictCode="tm_project_system,system_name,id" placeholder="请选择系统" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="接口名称" v-bind="validateInfos.apiName">
            <a-input v-model:value="formData.apiName" placeholder="请输入接口名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="请求方法" v-bind="validateInfos.requestMethods">
	          <j-dict-select-tag v-model:value="formData.requestMethods" dictCode="request_method" placeholder="请选择请求方法" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="请求风格" v-bind="validateInfos.requestStyle">
	          <j-dict-select-tag v-model:value="formData.requestStyle" dictCode="request_style" placeholder="请选择请求风格" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="关联功能" v-bind="validateInfos.functionId">
            <a-input v-model:value="formData.functionId" placeholder="请输入关联功能" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="url" v-bind="validateInfos.url">
            <a-input v-model:value="formData.url" placeholder="请输入url" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="数据格式" v-bind="validateInfos.requestDataType">
	          <j-dict-select-tag v-model:value="formData.requestDataType" dictCode="request_data_type" placeholder="请选择数据格式" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="描述" v-bind="validateInfos.description">
	          <a-textarea v-model:value="formData.description" :rows="4" placeholder="请输入描述" :disabled="disabled"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="请求头" key="interfaceHeader" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="interfaceHeaderTableRef"
          :loading="interfaceHeaderTable.loading"
          :columns="interfaceHeaderTable.columns"
          :dataSource="interfaceHeaderTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="Params" key="interfaceGetParam" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="interfaceGetParamTableRef"
          :loading="interfaceGetParamTable.loading"
          :columns="interfaceGetParamTable.columns"
          :dataSource="interfaceGetParamTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="Body" key="interfacePostParam" :forceRender="true">
        <interface-post-param-form ref="interfacePostParamFormRef" :disabled="disabled"></interface-post-param-form>
      </a-tab-pane>
      <a-tab-pane tab="前置操作" key="interfacePreOperation" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="interfacePreOperationTableRef"
          :loading="interfacePreOperationTable.loading"
          :columns="interfacePreOperationTable.columns"
          :dataSource="interfacePreOperationTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="后置操作" key="interfacePostOperation" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="interfacePostOperationTableRef"
          :loading="interfacePostOperationTable.loading"
          :columns="interfacePostOperationTable.columns"
          :dataSource="interfacePostOperationTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryInterfaceHeaderListByMainId, queryInterfaceGetParamListByMainId, queryInterfacePreOperationListByMainId, queryInterfacePostOperationListByMainId, queryDataById, saveOrUpdate } from '../InterfaceTest.api';
  import InterfacePostParamForm from './InterfacePostParamForm.vue'
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {interfaceHeaderColumns, interfaceGetParamColumns, interfacePreOperationColumns, interfacePostOperationColumns} from '../InterfaceTest.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "InterfaceTestForm",
    components:{
      JDictSelectTag,
      JVxeTable,
      InterfacePostParamForm,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const interfaceHeaderTableRef = ref();
      const interfaceHeaderTable = reactive<Record<string, any>>({
        loading: false,
        columns: interfaceHeaderColumns,
        dataSource: []
      });
      const interfaceGetParamTableRef = ref();
      const interfaceGetParamTable = reactive<Record<string, any>>({
        loading: false,
        columns: interfaceGetParamColumns,
        dataSource: []
      });
      const interfacePostParamFormRef = ref();
      const interfacePreOperationTableRef = ref();
      const interfacePreOperationTable = reactive<Record<string, any>>({
        loading: false,
        columns: interfacePreOperationColumns,
        dataSource: []
      });
      const interfacePostOperationTableRef = ref();
      const interfacePostOperationTable = reactive<Record<string, any>>({
        loading: false,
        columns: interfacePostOperationColumns,
        dataSource: []
      });
      const activeKey = ref('interfaceHeader');
      const formData = reactive<Record<string, any>>({
        id: '',
        projectId: '',   
        projectSystemId: '',   
        apiName: '',   
        requestMethods: '',   
        requestStyle: '',   
        functionId: '',   
        url: '',   
        requestDataType: '',   
        description: '',   
      });

      //表单验证
      const validatorRules = reactive({
        projectId: [{ required: true, message: '请输入项目!'},],
        projectSystemId: [{ required: true, message: '请输入系统!'},],
        apiName: [{ required: true, message: '请输入接口名称!'},],
        requestMethods: [{ required: true, message: '请输入请求方法!'},],
        requestStyle: [{ required: true, message: '请输入请求风格!'},],
        functionId: [{ required: true, message: '请输入关联功能!'},],
        url: [{ required: true, message: '请输入url!'},],
        requestDataType: [{ required: true, message: '请输入数据格式!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        // labelCol: {xs: {span: 24}, sm: {span: 5}},
        // wrapperCol: {xs: {span: 24}, sm: {span: 16}},
        labelCol: {style: { width: '100px' }},
        wrapperCol: { },
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        interfaceHeaderTable.dataSource = [];
        interfaceGetParamTable.dataSource = [];
        interfacePostParamFormRef.value.initFormData();
        interfacePreOperationTable.dataSource = [];
        interfacePostOperationTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const interfaceHeaderDataList = await queryInterfaceHeaderListByMainId(row['id']);
        interfaceHeaderTable.dataSource = [...interfaceHeaderDataList];
        const interfaceGetParamDataList = await queryInterfaceGetParamListByMainId(row['id']);
        interfaceGetParamTable.dataSource = [...interfaceGetParamDataList];
        await interfacePostParamFormRef.value.initFormData(row['id']);
        const interfacePreOperationDataList = await queryInterfacePreOperationListByMainId(row['id']);
        interfacePreOperationTable.dataSource = [...interfacePreOperationDataList];
        const interfacePostOperationDataList = await queryInterfacePostOperationListByMainId(row['id']);
        interfacePostOperationTable.dataSource = [...interfacePostOperationDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'interfaceHeader': interfaceHeaderTableRef,
        'interfaceGetParam': interfaceGetParamTableRef,
        'interfacePostParam': interfacePostParamFormRef,
        'interfacePreOperation': interfacePreOperationTableRef,
        'interfacePostOperation': interfacePostOperationTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        interfaceHeaderTableRef,
        interfaceHeaderTable,
        interfaceGetParamTableRef,
        interfaceGetParamTable,
        interfacePostParamFormRef,
        interfacePreOperationTableRef,
        interfacePreOperationTable,
        interfacePostOperationTableRef,
        interfacePostOperationTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>